package com.fruit.service.order.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.fruit.mapper.order.LogisticsMapper;
import com.fruit.mapper.order.MailOrderMapper;
import com.fruit.pojo.address.Address;
import com.fruit.pojo.logistics.Logistics;
import com.fruit.pojo.logistics.LogisticsOrder;
import com.fruit.pojo.logistics.LogisticsType;
import com.fruit.pojo.logistics.SysAddress;
import com.fruit.pojo.logistics.SysLogistics;
import com.fruit.pojo.logistics.SysLogisticsOrderResponse;
import com.fruit.pojo.logistics.SysNewDeliver;
import com.fruit.pojo.logistics.SysNewDeliverData;
import com.fruit.pojo.logistics.SysNewDeliverResponse;
import com.fruit.pojo.order.MailOrder;
import com.fruit.pojo.order.MailOrderSummary;
import com.fruit.pojo.rights.UserGoodsRights;
import com.fruit.service.logistics.LogisticsService;
import com.fruit.service.order.MailOrderManager;
import com.fruit.service.rights.UserRightsManager;
import com.fruit.service.user.UserManager;
import com.fruit.util.CustomUtil;
import com.fruit.util.DataUtil;
import com.fruit.util.DateUtil;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;
import com.joe.utils.common.DateUtil.DateUnit;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * 寄回订单业务逻辑类
 *
 * @author shibeilei
 * @version 2018.01.02 17:01
 *
 */
@Slf4j
@Service
public class MailOrderService implements MailOrderManager {

	@Autowired
	private MailOrderMapper mailOrderMapper;

	@Autowired
	private LogisticsMapper logisticsMapper;

	@Autowired
	private UserManager userService;

	@Autowired
	private UserRightsManager userRightsManager;

	@Autowired
	private LogisticsService logisticsService;

	@Value("${order_pre}")
	private String orderPre;

	@Value("${j_company}")
	private String jCompany;

	@Value("${com.fruit.logistics.sf.custid}")
	private String custid;

	@Override
	public Map<String, Object> getMailOrderList(String tradeId, Map<String, Object> params) {
		Map<String, Object> resMap = new HashMap<>();
		try {
			log.info("[{}]-【查看寄回订单列表】-【查看权益信息】", tradeId);
			String orderGoodsId = String.valueOf(params.get("orderGoodsId"));
			UserGoodsRights userRight = userRightsManager.getRightByOrderGoodsId(Integer.parseInt(orderGoodsId));
			log.info("[{}]-【查看寄回订单列表】", tradeId);
			List<MailOrder> mailOrderList = mailOrderMapper.getMailOrderList(params);
			for (int i = 0; i < mailOrderList.size(); i++) {
				MailOrder mailOrder = mailOrderList.get(i);
				if (StringUtils.isNoneBlank(mailOrder.getRealHarvestTime())
						&& StringUtils.isNoneBlank(mailOrder.getAddressUpdateEndTime())) {
					if (DateUtil.compareDate(mailOrder.getAddressUpdateEndTime(), DateUtil.getDay())) {
						mailOrder.setIsState("01");
					} else {
						mailOrder.setIsState("00");
					}
				} else {
					mailOrder.setIsState("01");
				}
				if (StringUtils.isNoneBlank(mailOrder.getAddressUpdateEndTime())) {
					// 如果当前时间小于当前截至时间的话 那么 通告时间 是当前的最后修改时间
					if (DateUtil.compareDate(mailOrder.getAddressUpdateEndTime(), DateUtil.getDay())) {
						String chTime = DateUtil.ChTime(mailOrder.getAddressUpdateEndTime());
						log.info("[{}]-【查看寄回订单列表】" + "【最后修改截至日期】", chTime);
						// 截取时间的时候月份是带0的 所以在截取的时候 只要月份和日的时候 就要把0给去掉
						String sub = chTime.substring(5, chTime.length() - 5);
						log.info("[{}]-【查看寄回订单列表】" + "【截取月份的 查看月份前面是否带有0】", sub);
						if ("0".equals(sub)) {
							userRight.setNoticeEndTime(chTime.substring(6, chTime.length()));// 有时间
							log.info("[{}]-【查看寄回订单列表】" + "【截取月份的 查看月份前面带有0 则不截取0】", userRight.getNoticeEndTime());
						} else {
							userRight.setNoticeEndTime(chTime.substring(5, chTime.length()));// 有时间
						}
						int num = i + 1;
						userRight.setBatch(num + "");
					} else {
						userRight.setNoticeEndTime("0");// 没有时间
						log.info("[{}]-【查看寄回订单列表】" + "【没有最后修改截至日期】", tradeId);
					}
				} else {
					userRight.setNoticeEndTime("0");// 没有时间
					log.info("[{}]-【查看寄回订单列表】" + "【没有采摘时间】", tradeId);
				}
			}
			resMap.put("mailOrderList", mailOrderList);
			resMap.put("userRight", userRight);
			resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "查看成功!"));
			log.info("[{}]-【查看寄回订单列表】-【成功】", tradeId);
			return resMap;
		} catch (Exception e) {
			e.printStackTrace();
			// 异常处理
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统异常!"));
			return resMap;
		}
	}

	@Override
	public Map<String, Object> updateMailOrderAddress(String tradeId, Map<String, Object> params) {
		Map<String, Object> resMap = new HashMap<>();
		try {
			long id = (long) params.get("id");

			log.info("[{}]-【修改寄回订单地址】-【订单ID：{}】", tradeId, id);
			log.info("[{}]-【修改寄回订单地址】-【查询寄回订单】", tradeId);
			MailOrder mo = mailOrderMapper.getMailOrderById(id);
			if (mo == null) {
				log.error("[{}]-【修改寄回订单地址】-【订单不存在】", tradeId);
				resMap.put("result",
						ResultUtil.initResult(ResultInfo.ERROR, "exception", "订单不存在!", null, ResultInfo.ROLLBACK));
				return resMap;
			} else {
				if (StringUtils.isNoneBlank(mo.getAddressUpdateEndTime())) {
					if (DateUtil.compareDate(DateUtil.getDay(), mo.getAddressUpdateEndTime())) {
						log.error("[{}]-【修改寄回订单地址】-【当前时间已经超过截至修改时间，不能进行修改地址】", tradeId);
						resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception",
								"当前时间已经超过截至修改时间，不能进行修改地址", null, ResultInfo.ROLLBACK));
						return resMap;
					}
				}
				if (!"00".equals(mo.getState())) {
					log.error("[{}]-【修改寄回订单地址】-【当前发货状态不是未发货状态】", tradeId);
					resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "该收货地址不能修改", null,
							ResultInfo.ROLLBACK));
					return resMap;
				}
			}
			int addressId = (int) params.get("addressId");
			log.info("[{}]-【修改寄回订单地址】-【查询收货地址】", tradeId);
			Address address = userService.getAddressById(addressId);
			if (address == null) {
				log.error("[{}]-【修改寄回订单地址】-【收货地址不存在】", tradeId);
				resMap.put("result",
						ResultUtil.initResult(ResultInfo.ERROR, "exception", "收货地址不存在!", null, ResultInfo.ROLLBACK));
				return resMap;
			}
			log.info("[{}]-【查看物流是否可达】");
			resMap = getLogisticsDoList(tradeId, mo.getBaseId(), addressId);
			ResultInfo ri = (ResultInfo)resMap.get("result");
			if (ResultInfo.ERROR.equals(ri.getState())) {
				return resMap;
			}
			
			mo.setCityId(address.getCityId());
			mo.setProvinceId(address.getProvinceId());
			mo.setCountryId(address.getCountryId());
			mo.setTownId(address.getTownId());
			mo.setReceiverName(address.getName());
			mo.setReceiverPhone(address.getPhone());
			mo.setReceiverAddress(address.getAddress());
			int num = mailOrderMapper.updateMailOrderAddress(mo);
			if (num > 0) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "修改成功!"));
			} else {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "OK", "修改失败!"));
			}
			return resMap;
		} catch (Exception e) {
			e.printStackTrace();
			// 异常处理
			resMap.put("result",
					ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统异常!", null, ResultInfo.ROLLBACK));
			return resMap;
		} finally {
			ResultInfo ri = (ResultInfo) resMap.get("result");
			if (ResultInfo.ROLLBACK.equals(ri.getIsRollBack())) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
			log.info("[{}]-【修改寄回订单地址】-【成功】", tradeId);
		}
	}

	@Override
	public List<MailOrder> getMailOrder(String tradeId, Map<String, Object> params) {
		List<MailOrder> mailOrderList = mailOrderMapper.getMailOrderList(params);
		return mailOrderList;
	}

	@Override
	public Map<String, Object> getMailOrderListByBaseId(String tradeId, Map<String, Object> params) {
		Map<String, Object> resMap = new HashMap<>();
		String state = (String) params.get("state");
		List<MailOrder> mailOrderList = null;
		params.put("curTime", DateUtil.getTime());
		params.put("errorState", "00");
		if ("00".equals(state)) {
			log.info("[{}]-【查看未发货订单列表】-【开始】", tradeId);
			mailOrderList = mailOrderMapper.getMailOrderListNotDeliverByBaseId(params);
		} else if ("02".equals(state)) {
			log.info("[{}]-【查看已发货订单列表】-【开始】", tradeId);
			mailOrderList = mailOrderMapper.getMailOrderListDeliverByBaseId(params);
		}

		resMap.put("mailOrderList", mailOrderList);
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "查看成功!"));
		log.info("[{}]-【查看未/已发货订单列表】-【成功】", tradeId);
		return resMap;
	}
	
	@Override
	public Map<String, Object> getErrorMailOrderListByBaseId(String tradeId, Map<String, Object> params) {
		Map<String, Object> resMap = new HashMap<>();
		List<MailOrder> mailOrderList = null;
		params.put("curTime", DateUtil.getTime());
		params.put("errorState", "01");
		params.put("state", "02");
		log.info("[{}]-【查看异常订单列表】-【开始】", tradeId);
		mailOrderList = mailOrderMapper.getMailOrderListDeliverByBaseId(params);

		resMap.put("mailOrderList", mailOrderList);
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "查看成功!"));
		log.info("[{}]-【查看异常订单列表】-【成功】", tradeId);
		return resMap;
	}

	@Override
	public Map<String, Object> checkMailOrder(String tradeId, Map<String, Object> params) {
		Map<String, Object> resMap = new HashMap<>();
		Integer[] ids = (Integer[]) params.get("ids");
		log.info("[{}]-【检测订单是否能发货】-【订单id:[{}]】-【开始】", tradeId, ids);
		params.put("errorState", "00");
		int num = mailOrderMapper.getMailOrderCntByIds(params);
		if (ids.length != num) {
			if (ids.length == 1) {
				log.error("[{}]-【检测订单是否能发货】-【检测订单状态】-【订单已发货或异常】", tradeId);
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "订单已派发或异常，你可以正常派发其他订单"));
				return resMap;
			}
			log.error("[{}]-【检测订单是否能发货】-【检测订单状态】-【订单不能合并】", tradeId);
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "订单不能合并"));
			return resMap;
		}

		log.info("[{}]-【检测订单是否能发货】-【检测收货信息】", tradeId);
		List<MailOrder> moList = mailOrderMapper.getMailOrderMergeListByIds(params);

		if (moList == null || moList.size() != 1) {
			log.error("[{}]-【检测订单是否能发货】-【检测收货信息】-【订单不能合并】", tradeId);
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "订单不能合并"));
			return resMap;
		}
		resMap.put("mailOrder", moList.get(0));
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "查看成功!"));
		log.info("[{}]-【检测订单是否能发货】-【检测成功】", tradeId);
		return resMap;
	}

	@Override
	public Map<String, Object> getLogisticsListByMailOrder(String tradeId, Map<String, Object> params) {
		log.info("[{}]-【获取有效物流】-【开始】", tradeId);
		Map<String, Object> resMap = new HashMap<>();
		resMap = checkMailOrder(tradeId, params);
		ResultInfo ri = (ResultInfo) resMap.get("result");
		if (ResultInfo.ERROR.equals(ri.getState())) {
			return resMap;
		}
		MailOrder mailOrder = (MailOrder) resMap.get("mailOrder");
		resMap.remove("mailOrder");
		log.info("[{}]-【获取有效物流】-【寄回订单:[{}]】-【开始】", tradeId, mailOrder);
		List<Logistics> ltList = logisticsMapper.getLogisticsList();
		if (ltList == null || ltList.size() == 0) {
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "没有匹配的物流"));
			return resMap;
		}
		ltList = getDeliver(mailOrder, ltList);

		if (ltList.isEmpty()) {
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "没有匹配的物流"));
			return resMap;
		}
		resMap.put("ltList", ltList);
		resMap.put("mailOrder", mailOrder);
		return resMap;
	}

	@Override
	public Map<String, Object> saveMailLogisticsOrder(String tradeId, Map<String, Object> params) {
		Map<String, Object> resMap = new HashMap<>();
		log.info("[{}]-【物流下单】-【开始】", tradeId);
		try {
			resMap = checkMailOrder(tradeId, params);
			ResultInfo ri = (ResultInfo) resMap.get("result");
			if (ResultInfo.ERROR.equals(ri.getState())) {
				return resMap;
			}
			MailOrder mailOrder = (MailOrder) resMap.get("mailOrder");
			mailOrder.setPackNum((int) params.get("packNum"));
			mailOrder.setWeight((BigDecimal) params.get("weight"));
			resMap.remove("mailOrder");
			log.info("[{}]-【物流下单】-【参数:[{}]】", tradeId, mailOrder);
			Logistics l = new Logistics();
			l.setType((String) params.get("type"));
			l = getDeliver(mailOrder, l);
			if (l == null) {
				log.error("[{}]-【物流下单】-【没有匹配的有效物流】", tradeId);
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "没有匹配的物流"));
				return resMap;
			}

			// 保存合并订单
			MailOrderSummary mailOrderSummary = new MailOrderSummary();
			mailOrderSummary.setjProvinceId(mailOrder.getjProvinceId());
			mailOrderSummary.setjCityId(mailOrder.getjCityId());
			mailOrderSummary.setjCountryId(mailOrder.getjCountryId());
			mailOrderSummary.setjTownId(mailOrder.getjTownId());
			mailOrderSummary.setDeliveryName(mailOrder.getDeliveryName());
			mailOrderSummary.setDeliveryPhone(mailOrder.getDeliveryPhone());
			mailOrderSummary.setDeliveryAddress(mailOrder.getDeliveryAddress());
			mailOrderSummary.setProvinceId(mailOrder.getProvinceId());
			mailOrderSummary.setCityId(mailOrder.getCityId());
			mailOrderSummary.setCountryId(mailOrder.getCountryId());
			mailOrderSummary.setTownId(mailOrder.getTownId());
			mailOrderSummary.setDescribe(mailOrder.getName());
			mailOrderSummary.setLogisticsType((String) params.get("type"));
			mailOrderSummary.setBaseId(mailOrder.getBaseId());
			mailOrderSummary.setPackNum((int) params.get("packNum"));
			mailOrderSummary.setWeight((BigDecimal) params.get("weight"));
			mailOrderSummary.setUnit("kg");
			mailOrderSummary.setLogisticsTime(DateUtil.getTime());
			mailOrderSummary.setReceiverName(mailOrder.getReceiverName());
			mailOrderSummary.setReceiverPhone(mailOrder.getReceiverPhone());
			mailOrderSummary.setReceiverAddress(mailOrder.getReceiverAddress());
			mailOrderSummary.setState("01");
			log.info("[{}]-【物流下单】-【生成合并订单记录-参数:[{}]】", tradeId, mailOrderSummary);
			int num = mailOrderMapper.saveMailOrderSummary(mailOrderSummary);
			mailOrderSummary.setCode(orderPre + CustomUtil.orderCode(3, mailOrder.getId(), mailOrder.getUserId()));
			num = mailOrderMapper.updateMailOrderSummaryCode(mailOrderSummary);
			if (num != 1) {
				log.error("[{}]-【物流下单】-【生成合并订单失败】", tradeId);
				resMap.put("result",
						ResultUtil.initResult(ResultInfo.ERROR, "error", "生成合并订单失败", null, ResultInfo.ROLLBACK));
				return resMap;
			}
			// 更新寄回订单汇总ID
			log.error("[{}]-【物流下单】-【更新寄回订单汇总ID】", tradeId);
			params.put("summaryId", mailOrderSummary.getId());
			params.put("oldSummaryId", 0);
			params.put("state", "02");
			params.put("curTime", DateUtil.getTime());
			num = mailOrderMapper.updateMailOrderSummaryId(params);
			Integer[] ids = (Integer[]) params.get("ids");
			log.info("id数量:{}-修改成功数量:{}", ids.length, num);
			if (ids.length != num) {
				log.error("[{}]-【物流下单】-【寄回订单更新失败】", tradeId);
				resMap.put("result",
						ResultUtil.initResult(ResultInfo.ERROR, "error", "寄回订单更新失败", null, ResultInfo.ROLLBACK));
				return resMap;
			}

			// 物流下单
			log.info("[{}]-【物流下单】-【调用顺丰物流接口】", tradeId);
			SysLogisticsOrderResponse sor = send(mailOrder, mailOrderSummary);
			if (!sor.isSuccess()) {
				log.error("[{}]-【物流下单】-【异常】-code-------{}", tradeId,
						sor.getE() != null ? sor.getE() : sor.getErrorCode());
				resMap.put("result",
						ResultUtil.initResult(ResultInfo.ERROR, "error", "顺丰物流调用异常", null, ResultInfo.ROLLBACK));
				return resMap;
			}
			log.info("[{}]-【物流下单】-【调用顺丰物流接口】-【返回结果-[{}]】", tradeId, sor);
			if (StringUtils.split(sor.getMailno(), ",").length == mailOrderSummary.getPackNum()) {
				// 生成物流订单
				String[] mailnos = StringUtils.split(sor.getMailno(), ",");
				List<LogisticsOrder> loList = new ArrayList<>();
				for (int i = 0; i < mailnos.length; i++) {
					LogisticsOrder lo = new LogisticsOrder();
					lo.setSummaryCode(mailOrderSummary.getCode());
					lo.setCode(mailOrderSummary.getCode() + "-" + (i + 1));
					lo.setMailNo(mailnos[i]);
					lo.setType(mailOrderSummary.getLogisticsType());
					if (i == 0) {
						lo.setIsParent("01");
					} else {
						lo.setIsParent("00");
					}

					lo.setCreateTime(DateUtil.getTime());
					lo.setUpdateTime(lo.getCreateTime());
					loList.add(lo);
				}
				Map<String, Object> loParams = new HashMap<>();
				loParams.put("loList", loList);
				num = logisticsMapper.insertLogisticsOrder(loParams);
				if (num != mailOrderSummary.getPackNum()) {
					// 异常订单
					log.error("[{}]-【物流下单】-【生成物流订单】-【异常】", tradeId);
					resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "logistics_error", "生成物流订单异常"));
					resMap.put("mos", mailOrderSummary);
					return resMap;

				}

			} else {
				// 异常订单
				log.error("[{}]-【物流下单】-【物流下单运单数量异常】-【异常】", tradeId);
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "logistics_error", "物流下单运单数量异常"));
				resMap.put("mos", mailOrderSummary);
				return resMap;
			}
			return resMap;
		} catch (Exception e) {
			log.error("[{}]-【物流下单】-【物流下单异常】-【异常】", tradeId);
			e.printStackTrace();
			resMap.put("result",
					ResultUtil.initResult(ResultInfo.ERROR, "exception", "物流下单异常", null, ResultInfo.ROLLBACK));
			return resMap;
		} finally {
			ResultInfo ri = (ResultInfo) resMap.get("result");
			if (ResultInfo.ROLLBACK.equals(ri.getIsRollBack())) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}
	}

	public void newHandelMailOrderError(MailOrderSummary mos) {
		String isRollBack = "00";
		try {
			Map<String, Object> params = new HashMap<>();
			params.put("id", mos.getId());
			params.put("state", "02");
			int num = mailOrderMapper.updateMailOrderSummaryState(params);
			if (num == 0) {
				isRollBack = "01";
				return;
			}
			params.clear();
			params.put("summaryId", mos.getId());
			params.put("errorState", "01");
			num = mailOrderMapper.updateMailOrderErrorState(params);
			if (num == 0) {
				isRollBack = "01";
				return;
			}
		} catch (Exception e) {
			isRollBack = "01";
			return;
		} finally {
			if (ResultInfo.ROLLBACK.equals(isRollBack)) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}
	}

	public void setAreaCode(MailOrder mailOrder) {
		Map<String, Object> params = new HashMap<>();
		params.clear();
		params.put("regionId", mailOrder.getjCityId());
		params.put("type", "00");
		Map<String, Object> regionCode = logisticsMapper.getAreaCodeByRegionId(params);
		if (regionCode != null) {
			mailOrder.setjAreaCode((String) regionCode.get("areaCode"));
		}

		params.clear();
		params.put("regionId", mailOrder.getCityId());
		params.put("type", "00");
		regionCode = logisticsMapper.getAreaCodeByRegionId(params);
		if (regionCode != null) {
			mailOrder.setAreaCode((String) regionCode.get("areaCode"));
		}

	}

	public SysLogisticsOrderResponse send(MailOrder mailOrder, MailOrderSummary mos) {

		LogisticsType s = LogisticsType.valueOf(mos.getLogisticsType());
		// 国内
		return logisticsService.send(s, createSysLogistics(mailOrder, mos));

	}

	public SysLogistics createSysLogistics(MailOrder mailOrder, MailOrderSummary mos) {
		SysLogistics logistics = new SysLogistics();
		logistics.setExpressType("2");
		logistics.setOrderid(mos.getCode());
		logistics.setJCompany(jCompany);
		logistics.setJContact(mailOrder.getDeliveryName());
		logistics.setJTel(mailOrder.getDeliveryPhone());
		logistics.setJCountry("中国");
		logistics.setJProvince(mailOrder.getjProvinceName());
		logistics.setJCity(mailOrder.getjCityName());
		logistics.setJCounty(mailOrder.getjCountryName());
		logistics.setJAddress(mailOrder.getDeliveryAddress());
		logistics.setDCompany(mailOrder.getReceiverName());
		logistics.setDContact(mailOrder.getReceiverName());
		logistics.setDTel(mailOrder.getReceiverPhone());
		logistics.setDMobile(mailOrder.getReceiverPhone());
		logistics.setDCountry("中国");
		logistics.setDProvince(mailOrder.getProvinceName());
		logistics.setDCity(mailOrder.getCityName());
		logistics.setDCounty(mailOrder.getCountryName());
		logistics.setDAddress(mailOrder.getReceiverAddress());
		logistics.setCustid(custid);
		logistics.setIsDocall((byte) 1);
		logistics.setParcelQuantity((byte) mos.getPackNum());
		return logistics;
	}

	public List<Logistics> getDeliver(MailOrder mailOrder, List<Logistics> ltList) {
		List<Logistics> dataList = new ArrayList<>(ltList.size());
		for (Logistics l : ltList) {
			l = getDeliver(mailOrder, l);
			if (l == null) {
				continue;
			}
			l.setIsPreferred("01");
			dataList.add(l);

		}
		return dataList;

	}

	public Logistics getDeliver(MailOrder mailOrder, Logistics l) {
		try {
			LogisticsType s = LogisticsType.valueOf(l.getType());
			SysNewDeliver deliver = new SysNewDeliver();
			String type;

			switch (s) {
			case SF:
				type = "2";
				deliver.setBusinessType(type);
				SysAddress destAddress = new SysAddress();
				destAddress.setProvince(mailOrder.getProvinceName());
				destAddress.setCity(mailOrder.getCityName());
				destAddress.setDistrict(mailOrder.getCountryName());
				destAddress.setAddress(mailOrder.getReceiverAddress());
				deliver.setDestAddress(destAddress);
				SysAddress srcAddress = new SysAddress();
				srcAddress.setProvince(mailOrder.getjProvinceName());
				srcAddress.setCity(mailOrder.getjCityName());
				srcAddress.setDistrict(mailOrder.getjCountryName());
				srcAddress.setAddress(mailOrder.getDeliveryAddress());
				deliver.setSrcAddress(srcAddress);
				break;
			default:
				type = null;
				return null;
			}

			SysNewDeliverResponse sr = logisticsService.searchDeliver(s, deliver);

			List<SysNewDeliverData> datas = sr.getDatas();
			if (datas == null) {
				log.error("时效查询-异常code-------{}", sr.getE() != null ? sr.getE() : sr.getErrorCode());
				return null;
			}

			SysNewDeliverData data = datas.stream().filter(d -> d.getBusinessType().equals(type)).findFirst().get();

			if (data == null) {
				log.error("时效查询-没有返回数据");
				return null;
			}
			l.setReadPrice(DataUtil.dealDouble(data.getPrice()));
			String format = com.joe.utils.common.DateUtil.BASE;
			String deleverTime = StringUtils.split(data.getDeliverTime(), ",")[0];
			log.info("预计到达时间[{}]", deleverTime);
			long time = com.joe.utils.common.DateUtil.calc(deleverTime,
					com.joe.utils.common.DateUtil.getFormatDate(format), format, DateUnit.HOUR);
			String readTime;
			long day = time / 24;

			if (time % 24 == 0) {
				readTime = (day == 0) ? String.valueOf(day) + ".5" : String.valueOf(day);
			} else {
				readTime = (time % 24 <= 12) ? String.valueOf(day) + ".5" : String.valueOf(day + 1);
			}

			l.setReadTime(readTime);

			return l;
		} catch (Exception e) {
			log.error("时效查询-异常code-------{}", e.getMessage());
			e.printStackTrace();
			return null;
		}

	}

	@Override
	public Map<String, Object> getMailOrderInfo(String tradeId, long id) {
		Map<String, Object> resMap = new HashMap<>();
		log.info("[{}]-【已发货寄回订单详情】-【开始】-【订单ID-[{}]】", tradeId, id);
		MailOrder mailOrder = mailOrderMapper.getMailOrderInfo(id);
		if (mailOrder == null) {
			log.error("[{}]-【已发货寄回订单详情】-【订单不存在】", tradeId);
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "order_not_exist", "订单不存在"));
			return resMap;
		}
		if (!"02".equals(mailOrder.getState())) {
			log.error("[{}]-【已发货寄回订单详情】-【订单状态错误】", tradeId);
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "order_state_error", "订单状态错误"));
			return resMap;
		}
		if ("01".equals(mailOrder.getErrorState()) || mailOrder.getSummaryId() == 0) {
			log.error("[{}]-【已发货寄回订单详情】-【订单异常】", tradeId);
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "order_exception", "订单异常"));
			return resMap;
		}
		if (com.joe.utils.common.DateUtil.isToday(mailOrder.getLogisticsTime(), com.joe.utils.common.DateUtil.BASE)) {
			mailOrder.setLogisticsTime("今天 " + mailOrder.getLogisticsTime().substring(11, 16));
		}
		List<LogisticsOrder> loList = logisticsMapper.getLogisticsOrderBySummaryCode(mailOrder.getSummaryCode());

		if (loList == null || loList.size() == 0) {
			log.error("[{}]-【已发货寄回订单详情】-【订单异常】", tradeId);
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "logistics_not_exist", "物流订单不存在"));
			return resMap;
		}
		resMap.put("mailOrder", mailOrder);
		resMap.put("loList", loList);
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "查询成功"));
		log.info("[{}]-【已发货寄回订单详情】-【查询成功】", tradeId);
		return resMap;
	}

	@Override
	public Map<String, Object> getLogisticsOrderList(String tradeId, Map<String, Object> params) {
		Map<String, Object> resMap = new HashMap<>();
		log.info("[{}]-【物流订单列表】-【开始】", tradeId);
		List<MailOrderSummary> mosList = mailOrderMapper.getMailOrderSummaryList(params);
		resMap.put("mosList", mosList);
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "查询成功"));
		log.info("[{}]-【物流订单列表】-【查询成功】", tradeId);
		return resMap;
	}

	@Override
	public Map<String, Object> getLogisticsOrderInfo(String tradeId, String code) {
		Map<String, Object> resMap = new HashMap<>();
		log.info("[{}]-【物流订单详情】-【code:[{}]】-【开始】", tradeId, code);
		MailOrderSummary mos = mailOrderMapper.getMailOrderSummaryInfo(code);
		if (mos == null) {
			log.error("[{}]-【物流订单详情】-【物流订单不存在】", tradeId);
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "order_not_exist", "物流订单不存在"));
			return resMap;
		}
		if (!"01".equals(mos.getState())) {
			log.error("[{}]-【物流订单详情】-【物流订单状态错误】", tradeId);
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "order_state_error", "物流订单状态错误"));
			return resMap;
		}
		List<MailOrder> moList = mailOrderMapper.getMailOrderBySummaryId(mos.getId());
		List<LogisticsOrder> loList = logisticsMapper.getLogisticsOrderBySummaryCode(mos.getCode());
		resMap.put("mos", mos);
		resMap.put("moList", moList);
		resMap.put("loList", loList);
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "查询成功"));
		log.info("[{}]-【物流订单详情】-【查询成功】", tradeId);
		return resMap;
	}

	@Override
	public Map<String, Object> getLogisticsDoList(String tradeId, MailOrder mailOrder) {
		Map<String, Object> resMap = new HashMap<>();
		log.info("[{}]-【获取有效物流】-【mailOrder:[{}]】-【开始】", tradeId, mailOrder);
		List<Logistics> ltList = logisticsMapper.getLogisticsList();
		if (ltList == null || ltList.size() == 0) {
			log.error("[{}]-【获取有效物流】-【没有匹配的物流】", tradeId);
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "没有匹配的物流"));
			return resMap;
		}

		ltList = getDeliver(mailOrder, ltList);

		if (ltList.isEmpty()) {
			log.error("[{}]-【获取有效物流】-【没有匹配的物流】", tradeId);
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "没有匹配的物流"));
			return resMap;
		}
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "查询成功"));
		log.info("[{}]-【获取有效物流】-【查询成功】", tradeId);
		return resMap;
	}

	@Override
	public Map<String, Object> getLogisticsDoList(String tradeId, int baseId, int addressId) {
		Map<String, Object> resMap = new HashMap<>();
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "查询成功"));
		log.info("[{}]-【获取有效物流】-【查询成功】", tradeId);
		return resMap;
		/*log.info("[{}]-【获取有效物流】-【baseId:[{}];addressId:[{}]】-【开始】", tradeId, baseId, addressId);
		MailOrder mailOrder = new MailOrder();
		Map<String, String> delivery = mailOrderMapper.getDeliverAddressByBaseId(baseId);
		if (delivery == null || delivery.isEmpty()) {
			log.error("[{}]-【获取有效物流】-【没有匹配的发货地】", tradeId);
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "没有匹配的发货地"));
			return resMap;
		}
		mailOrder.setjProvinceName(delivery.get("jProvinceName"));
		mailOrder.setjCityName(delivery.get("jCityName"));
		mailOrder.setjCountryName(delivery.get("jCountryName"));
		mailOrder.setjTownName(delivery.get("jTownName"));
		mailOrder.setDeliveryAddress(delivery.get("deliveryAddress"));

		// 验证收货地址
		Address address = userService.getAddressById(addressId);
		if (address == null) {
			log.error("[{}]-【获取有效物流】-【收货地址不能为空】", tradeId);
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "address_empty", "收货地址不能为空!"));
			return resMap;
		}
		mailOrder.setProvinceName(address.getProvinceName());
		mailOrder.setCityName(address.getCityName());
		mailOrder.setCountryName(address.getCountryName());
		mailOrder.setTownName(address.getTownName());
		mailOrder.setReceiverAddress(address.getAddress());

		return getLogisticsDoList(tradeId, mailOrder);*/
	}

	@Override
	public Map<String, Object> getAllDeliverStateNum(int baseId) {
		Map<String, Object> resMap = new HashMap<>();
		Map<String, Integer> allStateNum = mailOrderMapper.getAllDeliverStateNum(baseId);
		resMap.put("allStateNum", allStateNum);
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "查询成功"));
		return resMap;
	}

}
